package com.woniu.zsd.platform.interceptor;


import com.woniu.zsd.common.util.JWTUtil;
import com.woniu.zsd.common.util.RedisKey;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
@Component
@Configuration
public class AccountLoginInterceptor implements HandlerInterceptor {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private JWTUtil jwtUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //排除OPTIONS请求
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true;
        }

        //取出请求头
        String token = request.getHeader("token");
        System.out.println("token============="+token);
        if(token == null || token.isEmpty()){
            System.out.println("令牌不存在上面");
           // return true;
            throw new Exception("令牌不存在");
        }
        System.out.println("过kontoken");
        //判断短token是否到期
        if (stringRedisTemplate.hasKey(RedisKey.ACCESS_EXPIRE_TOKEN2(token))) {
            return true;
        }
        //判断短token是否过期
//        if(accesstoken == null || accesstoken.isEmpty()){
            synchronized (token.intern()){//加锁
               String refreshToken = stringRedisTemplate.opsForValue().get(RedisKey.ACCESS_REFRESH_TOKEN2(token));
                System.out.println("refreshToken=================================="+refreshToken);
               //解析长token
                Claims claims = jwtUtil.parseToken(refreshToken);
                //根据解析的长token生成长短token
                String newAccessToken = jwtUtil.createToken(claims, 30);
                String newRefreshtoken = jwtUtil.createToken(claims, 3*24+60);
                //通过响应头将jwt响应给客户端
                response.setHeader("token", newAccessToken);
                //在跨域请求访问时，必须公开请求头，前端才能获取到token
                response.setHeader("Access-Control-Expose-Headers", "token");
                //设置新的长短token
                stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE_TOKEN2(newAccessToken), "", 30, TimeUnit.MINUTES);
                stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_REFRESH_TOKEN2(newAccessToken), newRefreshtoken, 3, TimeUnit.DAYS);
                //为已过期的短token延长时间，为了防止并发情况下重复续期
                stringRedisTemplate.opsForValue().set(RedisKey.ACCESS_EXPIRE_TOKEN2(token),"",1,TimeUnit.MINUTES);

                //延时1分钟删除之前的长token，后面改成队列
                rabbitTemplate.convertAndSend("","delay_del_refresh_token_queue",RedisKey.ACCESS_REFRESH_TOKEN2(token));

//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            Thread.sleep(60000);//延时1分钟删除之前的长token
//                            stringRedisTemplate.delete(RedisKey.ACCESS_REFRESH_TOKEN2(token));
//                        } catch (Exception e) {
//                            throw new RuntimeException(e);
//                        }
//                    }
//                }).start();
            }
//        }
        return true;
    }
}
